package com.sdust.controller;

import com.sdust.constant.JwtClaimsConstant;
import com.sdust.constant.ParameterConstant;
import com.sdust.exception.LoginFailedException;
import com.sdust.pojos.dto.UserInfoDto;
import com.sdust.pojos.dto.UserLoginDto;
import com.sdust.pojos.entity.User;
import com.sdust.pojos.vo.UserLoginVo;
import com.sdust.properties.JwtProperties;
import com.sdust.result.Result;
import com.sdust.service.UserService;
import com.sdust.utils.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@RequiredArgsConstructor
@Tag(name = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Operation(summary = "微信用户登录接口")
    @PostMapping("/wxLogin")
    public Result login(@RequestBody UserLoginDto dto) {

        //微信登录
        User user = userService.wxLogin(dto);

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //构建vo返回对象
        UserLoginVo userLoginVO = UserLoginVo.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .avatarUrl(user.getAvatarUrl())
                .nickname(user.getName())
                .build();

        return Result.success(userLoginVO);

    }

    /**
     * 更新用户信息
     * @param dto
     * @return
     */
    @PostMapping("/updateInfo")
    public Result updateUserInfo(@RequestBody UserInfoDto dto) {

        //向消息队列发送用户信息修改的消息
        rabbitTemplate.convertAndSend(ParameterConstant.USER_INFO_MQ, dto);

        return userService.updateUserInfo(dto);
    }

}
